'use strict'
const db = uniCloud.database()
const _ = db.command
const MAX_LIMIT = 20
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  try {
    let body = event
    if (event.body) {
      body = JSON.parse(event.body)
    }

    const { uniIdToken, page = 1, pageSize = MAX_LIMIT } = body

    // 校验分页参数
    const parsedPage = parseInt(page)
    const parsedPageSize = parseInt(pageSize)
    if (isNaN(parsedPage) || parsedPage < 1 || isNaN(parsedPageSize) || parsedPageSize < 1 || parsedPageSize > MAX_LIMIT) {
      return {
        success: false,
        message: '分页参数非法，应为正整数且每页不超过 ' + MAX_LIMIT
      }
    }

    // 校验 token 并获取 uid
    const uniIDIns = uniID.createInstance({ context })
    const { code, uid } = await uniIDIns.checkToken(uniIdToken)
    if (code !== 0) {
      return {
        success: false,
        message: 'token 无效或已过期'
      }
    }

    // 获取预约记录
    const matchCondition = { user: uid }
    const recordRes = await db.collection('appoint_records')
      .where(matchCondition)
      .orderBy('create_time', 'desc')
      .skip((parsedPage - 1) * parsedPageSize)
      .limit(parsedPageSize)
      .get()

    const totalRes = await db.collection('appoint_records')
      .where(matchCondition)
      .count()

    const consultantIdList = [...new Set(recordRes.data.map(r => r.consultant))]

    // 查询咨询师信息：姓名和头像（avatar）
    const consultantRes = await db.collection('consultants')
      .where({ user_id: _.in(consultantIdList) })
      .field({ user_id: true, name: true, avatar: true })
      .get()

    const consultantMap = {}
    consultantRes.data.forEach(c => {
      consultantMap[c.user_id] = {
        name: c.name || '未知咨询师',
        avatar: c.avatar || ''
      }
    })

    // 查询用户头像（来自 uni-id-users.avatar_file.url）
    const userIdList = [uid, ...consultantIdList]
    const userInfoRes = await db.collection('uni-id-users')
      .where({ _id: _.in(userIdList) })
      .field({ _id: true, avatar_file: true })
      .get()

    const avatarMap = {}
    userInfoRes.data.forEach(user => {
      avatarMap[user._id] = user.avatar_file?.url || ''
    })

    // 构造返回数据
    const finalData = recordRes.data.map(item => ({
      ...item,
      consultantName: consultantMap[item.consultant]?.name || '未知咨询师',
      consultantAvatar: consultantMap[item.consultant]?.avatar || '',
      userAvatar: avatarMap[uid] || ''
    }))

    return {
      success: true,
      result: {
        total: totalRes.total,
        page: parsedPage,
        pageSize: parsedPageSize,
        data: finalData
      }
    }

  } catch (err) {
    console.error('获取用户预约记录失败:', err)
    return {
      success: false,
      message: '查询失败',
      error: err.message
    }
  }
}
